// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <string>

// #include <rapidjson/document.h>
// #include <rapidjson/error/en.h>
#include <simdjson.h>

#include "coin2/exchange/base/feed/latency_extractor.h"
#include "coin2/exchange/binance_base/feed_v1/processor.h"

namespace coin2::exchange::binance_base::feed_v1 {
namespace impl {

using coin2::exchange::base::executor::TopicRecordPacket;

class BinanceBaseLatencyExtractor : public base::feed::impl::LatencyExtractor {
 public:
  void ExtractLatency(std::shared_ptr<TopicRecordPacket> packet) override {

    if (!packet) { return ;}

    simdjson::padded_string buffer(packet->payload);
    simdjson::ondemand::document doc;
    if (auto err = parser_.iterate(buffer).get(doc); err) {
      LOG(ERROR) << "[BinanceCommonProcessor] unknown raw msg: " << packet->payload;
      return;
    }

    int64_t et = 0;
    int64_t val = 0;
    auto root = doc["data"]; 
    if (!root["T"].get_int64().get(val)) 
    {
        int64_t t_time = val * 1'000'000LL;
        if (t_time < packet->timestamp) et = t_time;
    }
    if (et == 0 && (!root["E"].get_int64().get(val)))
    {
      int64_t e_time = val * 1'000'000LL;
      if (e_time < packet->timestamp) et = e_time;
    }
    Update(packet->timestamp, et);
    LogPacket(packet);
  }
 private:
  simdjson::ondemand::parser parser_{};
};

}  // namespace impl
using impl::BinanceBaseLatencyExtractor;
}  // namespace coin2::exchange::binance_base::feed_v1
